<?php

namespace App\Http\Controllers;

use DB;
use Request;
use Validator;

use Laravel\Lumen\Routing\Controller;
class InvitationController extends BaseController
{
	public function index()
	{

          $userId = $_SESSION["ID"];

          $invitationResult = DB::select("SELECT id,head_dir,boy_name,girl_name,created_at
               FROM invitation 
               WHERE user_id = $userId
               AND is_delete = 0
               ORDER BY created_at DESC");

		return $this::jsonResponse(false,$invitationResult);
	}

	public function show($id)
	{
          $invitationResult = DB::select("SELECT invitation.*,music.dir AS music_dir 
               FROM invitation 
               LEFT JOIN music ON music.id = invitation.music_id
               WHERE invitation.id = $id");
          if(empty($invitationResult)){
              return $this::jsonResponse(true,[],"喜帖不存在。");
          }

          $invitationResult = $invitationResult[0];
          $invitationResult->pictures = DB::select("SELECT dir FROM picture
               WHERE invitation_id = $id
               AND is_visible = 1
               AND is_delete = 0
               ORDER BY weight DESC,created_at DESC");

          return $this::jsonResponse(false,$invitationResult);
	}

	public function store()
	{
        $input = Request::all();

        //参数检验
        $validator = Validator::make($input,
            [
                'model_id'       => 'integer|min:1',
                'boy_name'       => 'string|min:2',
                'girl_name'      => 'string|min:2',
                'wedding_time'   => 'date',
                'wedding_address'=> 'string|min:1',
                'music_id'       => 'integer',
                'music_dir'      => 'string',
                'head_dir'       => 'string',
                'video_dir'      => 'string',
                'wedding_video_dir'      => 'string',
                'map_dir'        => 'string',
                'boy_tel'        => 'string|size:11',
                'girl_tel'       => 'string|size:11',
                'boy_birth'      => 'date',
                'girl_birth'     => 'date',
                'traffic_way'    => 'string',
                'invit_letter'   => 'string',
                'thanks_letter'  => 'string',
                'pictures'       => 'array'
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        $userId = $_SESSION["ID"];
        $input['model_id']        = isset($input['model_id'])?$input['model_id']:0;
        $input['boy_name']        = isset($input['boy_name'])?$input['boy_name']:"";
        $input['girl_name']       = isset($input['girl_name'])?$input['girl_name']:"";
        $input['wedding_time']    = isset($input['wedding_time'])?$input['wedding_time']:"0000-00-00 00:00";
        $input['wedding_address'] = isset($input['wedding_address'])?$input['wedding_address']:"";

        $invitationData = [
               "user_id" => $userId
        ];
        $filedsArray = ['model_id','boy_name','girl_name','wedding_time','wedding_address',
          'music_id','music_dir','head_dir','video_dir','wedding_video_dir','map_dir','boy_tel','girl_tel','boy_birth',
          'girl_birth','traffic_way','invit_letter','thanks_letter'];
        foreach ($input as $key => $value) {
             if(in_array($key, $filedsArray))
               $invitationData[$key] = $value;
        }
        $invitationId = DB::table("invitation")->insertGetId($invitationData);

        if(isset($input["pictures"])){
             $picturesData = [];
             foreach ($input["pictures"] as $key => $value) {
                  if(isset($value["dir"]))
                    $picturesData[] = [
                         "invitation_id" => $invitationId,
                         "dir"           => $value["dir"],
                         "weight"        => isset($value["weight"])?$value["weight"]:0
                    ];
             }
             if(count($picturesData) >0)
               DB::table('picture')->insert($picturesData);
        }

        return $this::jsonResponse(false,$invitationId);
	}

	public function update($id)
	{
        $input = Request::all();

        //参数检验
        $validator = Validator::make($input,
            [
                'model_id'       => 'integer|min:1',
                'boy_name'       => 'string|min:2',
                'girl_name'      => 'string|min:2',
                'wedding_time'   => 'date',
                'wedding_address'=> 'string|min:1',
                'music_id'       => 'integer',
                'music_dir'      => 'string',
                'head_dir'       => 'string',
                'video_dir'      => 'string',
                'wedding_video_dir'      => 'string',
                'map_dir'        => 'string',
                'boy_tel'        => 'string|size:11',
                'girl_tel'       => 'string|size:11',
                'boy_birth'      => 'date',
                'girl_birth'     => 'date',
                'traffic_way'    => 'string',
                'invit_letter'   => 'string',
                'thanks_letter'  => 'string',
                'pictures'       => 'array'
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        $invitationData = [];
        $filedsArray = ['model_id','boy_name','girl_name','wedding_time','wedding_address',
          'music_id','music_dir','head_dir','video_dir','wedding_video_dir','map_dir','boy_tel','girl_tel','boy_birth',
          'girl_birth','traffic_way','invit_letter','thanks_letter'];
        foreach ($input as $key => $value) {
             if(in_array($key, $filedsArray))
               $invitationData[$key] = $value;
        }
        $result = DB::table("invitation")->where("id",$id)->update($invitationData);

        if(isset($input["pictures"])){
             DB::table('picture')->where("invitation_id",$id)->update(["is_delete"=>1]);
             $picturesData = [];
             foreach ($input["pictures"] as $key => $value) {
                  if(isset($value["dir"]))
                    $picturesData[] = [
                         "invitation_id" => $id,
                         "dir"           => $value["dir"],
                         "weight"        => isset($value["weight"])?$value["weight"]:0
                    ];
             }
             if(count($picturesData) >0)
               DB::table('picture')->insert($picturesData);
        }

        return $this::jsonResponse(false,$result);
	}

	public function destory($id)
	{
	    $result = DB::table('invitation')->where("id",$id)->update(["is_delete"=>1]);
	    DB::table('attend')->where("invitation_id",$id)->delete();
      DB::table('bless')->where("invitation_id",$id)->delete();

      return $this::jsonResponse(false,$result);
  }
}